package com.yuma.jol;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.openjdk.jol.info.ClassLayout;

import java.io.Serializable;


class A implements Serializable {

}

/**
 * 启动的时候注意加上JVM启动参数：-XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0
 * 关闭指针压缩再次测试 (-XX:-UseCompressedOops 默认开启)
 */
public class BiasedLockTest {

    public static void main(String[] args) throws InterruptedException {
        User lock = new User();
        System.out.println("抢占锁前lock的状态：" + lock.getObjectStruct());
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                synchronized (lock) {
                    if (i == 99) {
                        System.out.println("占有锁lock的状态：" + lock.getObjectStruct());
                    }
                }
            }
        }, "biased-lock-thread");
        thread.start();
        thread.join();
        System.out.println("释放锁后lock的状态：" + lock.getObjectStruct());
    }

    @ToString
    @Setter
    @Getter
    public static class User {
        private String userName;

        //对象结构字符串
        public String getObjectStruct() {
            return ClassLayout.parseInstance(this).toPrintable();
        }
    }
}